import os, sys, logging
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.1')

import settings
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from models import *
import os
from google.appengine.ext.webapp import template
import datetime
import calendar
# import logging

def overlap(rangeA, rangeB):
    return rangeA[0] < rangeB[1] and rangeB[0] < rangeA[1]

def create_calendar_data(committer=None, num_months=12):
    c = calendar.Calendar(6)
    calendar.setfirstweekday(6)
    months_completed = 0
    months = []
    now = datetime.datetime.now()
    month = now.month
    year = now.year
    end_month = month + num_months
    end_year = year
    if end_month > 12:
        end_month -= 12
        end_year += 1
        
    obligations = list(Obligation.gql('WHERE start >= :1', datetime.date(year, month, 1)))
    holidays = list(Holiday.gql('WHERE start >= :1', datetime.date(year, month, 1)))
    milestones = list(Milestone.gql('WHERE due >= :1', datetime.date(year, month, 1)))
    while months_completed < num_months:
        data = {
            'n': month,
            'month': calendar.month_name[month],
            'year': year,
            'weekheader': calendar.weekheader(3).split(' '),
            'weeks': []
        }
        for week in c.monthdatescalendar(year, month):
            week_data = []
            for day in week:
                date = day
                day = datetime.datetime(day.year, day.month, day.day)
                start = day
                end = start + datetime.timedelta(days=1) - datetime.timedelta(seconds=1)
                classes = []
                if day.month != month:
                    classes.append('hidden')
                if day.day == now.day and day.year == now.year:
                    classes.append('now')
                for obligation in obligations:
                    if overlap([start, end], [obligation.start, obligation.end]):
                        classes.append('obligation')
                        classes.append(obligation.type)
                for holiday in holidays:
                    if overlap([start, end], [holiday.start, holiday.end]):
                        classes.append('Holiday')
                for milestone in milestones:
                    if milestone.due == date:
                        classes.append('Milestone')
                    
                week_data.append({
                    'n': day.day,
                    'classes': ' '.join(classes),
                })
            data['weeks'].append(week_data)
        months.append(data)
        month += 1
        if month == 13:
            month = 1
            year += 1
        months_completed += 1
    return months

class CalendarHandler(webapp.RequestHandler):

    def get(self):
        path = os.path.join(os.path.dirname(__file__), '../templates/calendar.html')
        self.response.out.write(template.render(path, {
            'title': 'Calendar',
            'section': 'Calendar',
            'data': create_calendar_data(),
        }))

class DayHandler(webapp.RequestHandler):

    def get(self):
        path = os.path.join(os.path.dirname(__file__), '../templates/day.html')
        day = datetime.datetime(int(self.request.GET['year']), int(self.request.GET['month']), int(self.request.GET['day']))
        start = day
        end = start + datetime.timedelta(days=1) - datetime.timedelta(seconds=1)
        self.response.out.write(template.render(path, {
            'day': day.day,
            'month': day.month,
            'year': day.year,
            'milestones': list(Milestone.gql('WHERE due = :1', day)),
            'obligations': [o for o in Obligation.all() if overlap([start, end], [o.start, o.end])],
            'holidays': [o for o in Holiday.all() if overlap([start, end], [o.start, o.end])],
        }))

def main():
    application = webapp.WSGIApplication([('/calendar/', CalendarHandler),
    ('/calendar/day/', DayHandler)], 
        debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()